import UiKit from './ui-kit.js'
import querystring from 'querystring'
class Request {
	defaultOption = {
		method: "GET"
	}
	pageData = {};
	setDefaultOption(option) {
		this.defaultOption = option;
	}
	_combineOption(option) {
		Object.keys(this.defaultOption).forEach(k => {
			if (option[k] === undefined) {
				option[k] = this.defaultOption[k]
			}
		});
		if (this.defaultOption.data !== undefined) {
			if (option.data == undefined || option.data.length === 0) {
				option.data = this.defaultOption.data;
			} else {
				Object.keys(this.defaultOption.data).forEach(k => {
					if (option.data[k] === undefined) {
						option.data[k] = this.defaultOption.data[k]
					}
				});
			}
		}
	}
	_handleSuccess(response, option, resolve, reject) {
		// 非规则的直接返回
		const status = response.statusCode
		if ((response.data.success === undefined || response.data.success === true) && status >= 200 && status <
			300) {
			if (option.success) option.success(response);
			resolve(response);
		} else {
			if (option.fail) {
				option.fail(response);
			} else if (!option.cancelModal) {
				uni.showModal({
					content: response.data.message,
					showCancel: false
				});
			}
			reject(response)
		}
	}
	_handleFail(response, option, resolve, reject) {
		if (option.fail) {
			option.fail();
		} else if (!option.cancelModal) {
			let info = '';
			switch (response.data.code) {
				case 1001:
					info = '页面过期,请刷新';
					break;
				case 1002:
					info = '没有权限';
					break;
				case 1000:
				case 1003:
					info = response.data.message;
					break;
				default:
					info = '操作失败，请重新打开页面再试';
			}
			uni.showModal({
				content: info,
				showCancel: false
			});
		}
		reject(response)
	}
	async get(option) {
		UiKit.showLoading('加载中', true);
		this._combineOption(option);
		return new Promise((resolve, reject) => {
			uni.request({
				url: option.url,
				data: option.data,
				method: option.method,
				header: option.header,
				success: (res) => this._handleSuccess(res, option, resolve, reject),
				fail: (res) => this._handleFail(res, option, resolve, reject),
				complete: (res) => {
					UiKit.hideLoading()
				}
			})
		})
	};
	async post(option) {
		return await this.form(option);
	};
	async form(option) {
		option.method = option.method || 'POST';
		option.header = option.header || {
			"Content-Type": "application/x-www-form-urlencoded"
		};
		return await this.get(option);
	};
	file(option) {
		this._combineOption(option);
		UiKit.showLoading('加载中', true);

		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: option.url + "?" + querystring.stringify(option.data),
				header: option.header,
				name: option.name,
				filePath: option.filePath,
				success: (res) => {
					res.data = JSON.parse(res.data)
					this._handleSuccess(res, option, resolve, reject)
				},
				fail: (res) => this._handleFail(res, option, resolve, reject),
				complete: (res) => {
					UiKit.hideLoading()
				},
			})
		})
	}
	async page(option) {
		let newOption = JSON.parse(JSON.stringify(option));
		let savedData = this.pageData[option.flag];
		if (savedData) {
			if (option.next) {
				savedData.page++;
			} else {
				savedData.page = 1;
				savedData.time = new Date().getTime();
				savedData.data = [];
			}
		} else {
			savedData = {};
			this.pageData[option.flag] = savedData;
			savedData.page = 1;
			savedData.time = new Date().getTime();
			savedData.data = [];
		}
		if (!newOption.data) {
			newOption.data = {}
		}
		newOption.data.page = savedData.page;
		newOption.data.time = savedData.time;
		let response = await this.get(newOption);
		if (response.data.total != undefined) {
			savedData.data = savedData.data.concat(response.data.data);
			savedData.total = response.data.total;
		} else {
			//兼容旧数据格式
			if (response.data.data.list) {
				savedData.data = savedData.data.concat(response.data.data.list);
				savedData.total = response.data.data.total;
			} else {
				savedData.data = savedData.data.concat(response.data.data.rows);
				savedData.total = response.data.data.count;
			}

		}
		uni.showToast({
			title: '合计' + savedData.total + '条数据',
			duration: 2000
		})
		if (option.success) {
			option.success(savedData);
		}
		return savedData;
	}
}
export default Request;
